/*
 * Copyright (C) 2007-2008  Hylke van der Schaaf
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, in version 3 of the License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package hextd.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

abstract public class MapLoader {

	protected Map<Integer, String> categories;
	protected Map<Integer, MapInfo> mapCache = new HashMap<Integer, MapInfo>();
	protected Map<String, MapInfo> mapCacheLocal = new HashMap<String, MapInfo>();
	protected List<MapInfo> mapList = null;
	protected List<MapInfo> mapListLocal = new ArrayList<MapInfo>();
	protected URL localMapContextUrl;

	abstract public MapInfo getMap(int mapId);

	public MapInfo getMap(String fileName) {
		MapInfo info = mapCacheLocal.get(fileName);
		if (info != null && info.getContent() == null) {
			try {
				//System.out.println("HexTD::FetchFromUrl::file = " + fetchUrl.toString());
				BufferedReader bufferedreader;
				URL fetchUrl = new URL(localMapContextUrl, info.fileName);
				URLConnection urlconnection = fetchUrl.openConnection();
				if (urlconnection.getContentEncoding() != null) {
					bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), urlconnection.getContentEncoding()));
				} else {
					bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), "utf-8"));
				}
				String line;
				StringBuilder mapContent = new StringBuilder();
				while ((line = bufferedreader.readLine()) != null) {
					mapContent.append(line);
					mapContent.append("\n");
				}
				info.setContent(mapContent.toString());
			} catch (IOException _ex) {
				System.err.println("HexTD::readFile:: Can't read from " + info.fileName);
			}
		}
		return info;
	}

	/**
	 * Tries to load a local map and adds it to the map cache if successful.
	 * @param fileName
	 * @param contextDir
	 */
	protected void tryLoadLocalFile(String fileName, URL contextDir) {

		MapInfo levelInfo = new MapInfo();
		String[] split = fileName.split(" ");
		fileName = split[0];
		if (split[0].length() == 2 && split[0].charAt(0) == 'c') {
			int cat = Integer.parseInt(split[0].substring(1));
			if (categories == null) {
				categories = new HashMap<Integer, String>();
			}
			categories.put(cat, split[1]);
		} else {
			int cat = 0;
			int id = 0;
			if (split.length > 1) {
				id = Integer.parseInt(split[1]);
				cat = Integer.parseInt(split[2]);
			}
			if (split.length > 3) {
				int parseInt = Integer.parseInt(split[3]);
				if (parseInt > 0) {
					levelInfo.preReq.add(-parseInt);
				}
			}
			if (split.length > 4) {
				int parseInt = Integer.parseInt(split[4]);
				if (parseInt > 0) {
					levelInfo.nextMap = -parseInt;
				}
			}
			levelInfo.fileName = fileName;
			levelInfo.category = cat;

			levelInfo.mapId = -id;
			mapListLocal.add(levelInfo);
			mapCache.put(levelInfo.mapId, levelInfo);
			mapCacheLocal.put(fileName, levelInfo);

			// getMap will load the content of the map
			getMap(fileName);
			// getMapData will parse the content of the map and fill the mapInfo
			GameMap mapData = levelInfo.getMapData();

			if (levelInfo.players == 0) {
				levelInfo.players = 1;
			}

			System.out.println("ClientMapLoader:tryLoadFile: added " + levelInfo.players + " player map " + levelInfo.title + " to index.");
		}
	}
}
